package com.sjc.grpc.server.grpc;

import com.sjc.demo.java.grpc.rpc.HelloServiceGrpc;
import com.sjc.grpc.server.service.RpcHelloServiceImpl;
import io.grpc.BindableService;
import io.grpc.Server;
import io.grpc.ServerBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

@Component
public class GrpcServer {

    private static Logger log = LoggerFactory.getLogger(GrpcServer.class);

    @Value("${grpc.port}")
    private int port;
    @Resource
    private RpcHelloServiceImpl helloServiceImpl;

    private Server server;

    @PostConstruct
    public void init(){
        // 指定监听端口和RPC服务的业务逻辑实现类rpcHelloService
        server = ServerBuilder.forPort(port).addService(helloServiceImpl).build();
    }

    public void stop(){
        server.shutdown();
    }

    /**
     * 开启在指定端口监听Grpc客户端的RPC方法调用请求
     */
    public void start(){
        try{
            server.start();
            log.info("GrpcServer listen on {}", port);
            server.awaitTermination();
        }catch (Exception e){
            log.error("GrpcServer listen on {}", port, e);
        }

        // 关闭回调hook
        Runtime.getRuntime().addShutdownHook(new Thread(){
            @Override
            public void run() {
                log.info("GrpcServer shutdown {}", port);
                GrpcServer.this.stop();
            }
        });
    }

}
